package com.example.security_demo.config;

import com.example.security_demo.sms.SmsAuthenticationFilter;
import com.example.security_demo.sms.SmsAuthenticationProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * spring security configuration
 *  如何禁用
 * 需要理解 spring security 配置文件理解
 *  默认的配置是什么
 * @author zzh
 * @date 2022/4/15
 * @since 1.0
 */
@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/sms/login", "/sms/loginOne", "/test/**", "/users/**").permitAll().anyRequest().authenticated()
                .and().csrf().disable();

        // 配置 过滤器
        http.addFilterBefore(smsAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
        http.authenticationProvider(new SmsAuthenticationProvider());


    }

    /**
     *  暴露  spring security中的 AuthenticationManager 对象，使得的用户可以在需要时进行对象注入
     *  例如：
     *  <html>
     *     <></> @autowired <br/>
     *      AuthenticationManager authenticationManager;
     *      <html/>
     * @return AuthenticationManager
     * @throws Exception 异常
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 配置 filer, 此处要注意： 一定要注入AuthenticationManager
     */
    @Bean
    public SmsAuthenticationFilter smsAuthenticationFilter() throws Exception {
        SmsAuthenticationFilter smsAuthenticationFilter = new SmsAuthenticationFilter();
        smsAuthenticationFilter.setAuthenticationManager(authenticationManagerBean());
        smsAuthenticationFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler());
        return smsAuthenticationFilter;
    }


    @Bean
    public AuthenticationFailureHandler authenticationFailureHandler() {
        return (request, response, exception) -> {

            response.setContentType("application/json;utf-8");
            response.getWriter().write("Exception Handler");
        };
    }

    @Bean
    public AuthenticationSuccessHandler authenticationSuccessHandler() {

        return (request, response, authentication) -> {

            response.setContentType("application/json;utf-8");
            response.getWriter().write("success Handler!!!");
        };
    }
}
